// React基础组件
import React from 'react'
// dva 连接组件 - 连接route和model
import { connect } from 'dva'
// 引入antd的组件
import { Form, Popconfirm, Upload, message, Button, Modal, Row, Col, Input, Divider } from 'antd'
//导入路由组件，用于跳转等
import { Link, hashHistory } from 'dva/router'
// 导入项目全局配置文件
import config from 'config/config'

// 引入model取值工具方法
import { mapStateToProps } from 'utils/view_utils'
import { reqInform } from 'utils/notification'
// 当前组件样式
import styles from './giftRegistrationListStyle.less'
import Uploader from '../../../../widget/Upload'
import ListPage from 'widget/PageTmpl/ListPage'
import cx from 'classnames'
import $ from 'jquery'
import Cookie from 'js-cookie'
import { download } from 'utils/util'
//权限管理
import FlagBtn from 'widget/FlagBtn/FlagView'

const FormItem = Form.Item
/**
 * description 路由视图及事件处理
 * dispatch 分发到models中的effects对应事件名
 * model 用于获取models中state定义的数据
 * form 表单对象
 */

const formItemLayout = {
  labelCol: { span: 4 },
  wrapperCol: { span: 16 },
}
const formItemLayout2 = {
  labelCol: { span: 3 },
  wrapperCol: { span: 16 },
}
const giftRegistrationListView = function({ dispatch, model, form}){
  // 表单的子函数
  const { resetFields, getFieldDecorator, validateFields, setFieldsValue } = form
  // 取出model对象，命名空间
  const { modelObj, namespace } = model
  // modelObj.xxx获取model中状态机的值
  let {regionList,biz,projectList,userLevel} = modelObj
  let accountId = JSON.parse(localStorage.getItem('navBar')).accountId || ""
  console.log('regionList',regionList)

  let option = [
    { value: 1, label: '上架' },
    { value: 0, label: '下架' },
  ]
  function detailSkip(type,giftId){
    // debugger
    hashHistory.push({
      pathname: '/home/infoAdmin/giftRegistrationDetail',
      query: { actionType: type, giftId }
    })
  }
  function giftInfoSkip(type,giftInfo){
    // debugger
    hashHistory.push({
      pathname: '/home/infoAdmin/giftReceiveInfo',
      query: { ...giftInfo }
    })
  }
  // 分页表格属性配置
  let pageProps = {
    // ---------- 界面部分 ----------
    'ui': {
      // 页面接口地址
      'api_url': 'admin/product/present/list',
      // "api_url": "admin/housetype/list",
      // 接口方式
      'method': 'POST',
      'app': 'isales-mgmt-application',
      // 接口参数
      'params': `accountId=${accountId}`,
      // 模拟数据 - 用于开发需要，若填充了上面的api_url之后，请将此项设置为null
      // "mockData": mockData,
      'mockData': null,
      // 查询栏
      'search_bar': {
        'fields': [
          {
            en_name: 'regionId',
            zh_name: '区域名称',
            elem_type: 'Select',
            elem_valid_type: 'string',
            cmpt_items: regionList,
          },
          {
            en_name: 'projectId',
            zh_name: '项目名称',
            elem_type: 'Select',
            elem_valid_type: 'string',
            cmpt_items: projectList,
            onFocus:()=>{
              if(biz.queryForm && biz.queryForm.regionId)
              {
                let data = regionList.filter(item=>{
                  return item.regionId == biz.queryForm.regionId
                })
                console.log('biz.queryForm.regionId',biz.queryForm.regionId)
                console.log('data',data)
                console.log('regionList',regionList)
                data[0].projectList.forEach((item,index)=>{
                  item.value = item.projectId
                  item.label = item.projectName
                  item.key = index
                })
                dispatch({
                  type: `${namespace}/updateStore`,
                  payload: {projectList:data[0].projectList}
                })
              }
            }
          },
          {
            en_name: 'name',
            zh_name: '礼品名称',
            elem_type: 'Input',
            elem_valid_type: 'string',
          },
          {
            en_name: 'shelfStatus',
            zh_name: '状态',
            elem_type: 'Select',
            cmpt_items: option,
            elem_valid_type: 'string',
          },
          {
            en_name: 'validTime',
            zh_name: '线上申请期限',
            elem_type: 'Date',
            format: 'YYYY-MM-DD',
            // query_format: "YYYY-MM-DD HH:mm:ss",   // 请求参数, 当请求参数和显示时格式不同可通过该参数区分
            // double: true,  // 日期范围组件 使用"YYYY-MM-DD HH:mm:ss"格式时, 显示不全时可使用该参数, 将占据两格位置
            split_keys: ['startOnlineTime', 'endOnlineTime'],
            elem_valid_type: 'string'
          }
        ],
        searchHandler: (p) => { // 自定义搜索按钮回调函数，点击搜索时触发
          console.log('search click', p)
        },
        resetHandler: (p) => { // 自定义重置按钮回调函数，点击重置时触发
          console.log('reset click', p)
        },
        searchCallback: params => { // 自定义搜索完成后的后调函数, 搜索完成后触发, 并将本次搜索的参数传入
          console.log('search finish', params)
        },
        pasteTargetList: [  // 列表组件中将输入框的en_name作为默认id(也可以通过id另外设置)
          'carName',  // 将需要粘贴事件拦截的输入框id以数组的形式传入, 该参数对应PasteFromClipboard组件的targetList参数
        ]
      },
      // 数据表格
      'table': {
        'status_params': 'status=0',
        'status_text': '全部',
        'scroll': { x: 2000 },
        'action_props': { width: 200 },
        // 表头字段列表"
        'fields': [
          {
            en_name: "key",
            zh_name: "序号",
            width: 60,
            render: (a, item, index, d, e, f) => {
              return index + 1
            },
          },
          {
            'en_name': 'name',
            'zh_name': '礼品名称',
            width: 200
          },
          {
            'en_name': 'usageScope',
            'zh_name': '适用范围',
            width: 100,
            render: (a, item, index, d, e, f) => {
              if(item.usageScope=='3'){
                return <div>集团</div>
              }
              else if(item.usageScope=='2'){
                return <div>区域</div>
              }
              else if(item.usageScope=='1'){
                return <div>项目</div>
              }else{
                return <div>-</div>
              }
            }
          },
          {
            'en_name': 'regionName',
            'zh_name': '所属区域',
            width: 200,
          },
          {
            'en_name': 'projectName',
            'zh_name': '所属项目',
            width: 200
          },
          {
            'en_name': 'totalStock',
            'zh_name': '总数量',
            width: 150,
            render: (a, item, index, d, e, f) => {
              if(item.totalStockType=='1'){
                return <div>{item.totalStock}</div>
              }else{
                return <div></div>
              }
            }
          },
          {
            'en_name': 'useCount',
            'zh_name': '已申请数量',
            width: 150,
          },
          {
            'en_name': 'availCount',
            'zh_name': '剩余库存量',
            width: 150,
            render: (a, item, index, d, e, f) => {
              if(item.totalStockType=='1'){
                return <div>{item.availCount}</div>
              }else{
                return <div></div>
              }
            }
          },
          {
            'en_name': 'totalStockType',
            'zh_name': '库存是否限量',
            width: 150,
            render: (a, item, index, d, e, f) => {
              if(item.totalStockType=='1'){
                return <div>限量</div>
              }else{
                return <div>不限量</div>
              }
            }
          },
          {
            'en_name': 'shelfStatus',
            'zh_name': '上架状态',
            width: 100,
            render: (text, record) => {
              return <div>
                {{ 1: '已上架', 0: '已下架' }[text] || ''}
              </div>
            }
          },
          {
            'en_name': 'endOnlineTime',
            'zh_name': '线上申请期限',
            width: 350,
            render: (text, item) => {
               return <div>{`${item.startOnlineTime.split(' ')[0] || ''}${item.endOnlineTime && ' ~ ' || ''}${item.endOnlineTime.split(' ')[0] || ''}`}</div>
            }
          },
          {
            'en_name': 'createTime',
            'zh_name': '创建时间',
            width: 250,
          },
          {
            'en_name': 'updateTime',
            'zh_name': '更新时间',
            width: 250,
          },
          {
            'en_name': 'updatePerson',
            'zh_name': '更新人',
            width: 200,
          },
          {
            en_name: "edit",
            zh_name: "操作",
            width: 160,
            fixed: 'right',
            render: (a, item, index, d, e, f) => {
              return (
                <span>
                  <FlagBtn node={3==item.productType?<span style={{ color: '#ccc' }}>查看礼品详情<span className="ant-divider" style={{ display: 'inline-block' }} /></span>:<a onClick={() => giftInfoSkip('check', item)}>查看礼品详情<span className="ant-divider" style={{ display: 'inline-block' }} /></a>} btnId={'20502'}> </FlagBtn>
                  <FlagBtn node={<a onClick={Number(item.usageScope)<=Number(userLevel)?() => detailSkip('edit', item.productId):() => detailSkip('look', item.productId)} style={{ display: 'inline-block' }}>{Number(item.usageScope) <= Number(userLevel)?'编辑':'查看'}</a>} btnId={'20503'}> </FlagBtn>
                </span>
              )
            },
          }

        ],

        // 'actions': [
        //   {
        //     func_name: 'bussinessDetail',
        //     label: '业务详情',
        //     render: (record) => {
        //       let linkQuery = {
        //         giftId:record.giftId,
        //         title:record.title,
        //         totalStock:record.totalStock,
        //         shelfStock:record.shelfStock,
        //         receiveCount:record.receiveCount,
        //       }
        //       return (
        //         <div>
        //           <FlagBtn node={<Link to='home/giftAdmin/giftDetail' query={{...linkQuery}}>查看记录详细<span className="ant-divider" style={{ display: 'inline-block' }} /></Link>} btnId={'20302'}> </FlagBtn>
        //           <FlagBtn node={<Link to='home/giftAdmin/giftAdd' query={{ giftId: record.giftId,actionType:'edit'}}>编辑<span className="ant-divider" style={{ display: 'inline-block' }} /></Link>} btnId={'20303'}> </FlagBtn>
        //           <FlagBtn node={<Popconfirm Collapse title='确定要删除该优惠券吗？' okText='确定' cancelText='取消'
        //             onConfirm={() => {
        //               dispatch({
        //                 type: `${namespace}/deleteGift`,
        //                 payload: {  giftId: record.giftId }
        //               })
        //             }}>
        //             <Link>删除</Link>
        //           </Popconfirm>} btnId={'20305'}> </FlagBtn>
        //         </div>
        //       )
        //     }
        //   }
        // ],
      },
      // 操作栏
      action_bar: [
        {
          'func_name': 'add',
          'label': '新增礼品',
          btnId: '20501',
          'type': 'primary',
          'onClick': (e) => {
            detailSkip("add")
          }
        },
      ],
    },
  }
  if (!!modelObj.biz) {
    pageProps.biz = modelObj.biz
    pageProps.biz.syncBackCbf = (biz) => {
      dispatch({
        type: `${namespace}/updateStore`,
        payload: { biz }
      })
    }
  }
  return (
    <div className={cx('pageLayout')}>
      <ListPage pageProps={pageProps} />
    </div>
  )
}

export default connect(mapStateToProps)(Form.create()(giftRegistrationListView))
